import type { Note, AppSettings, DEFAULT_SETTINGS } from '@/types/note'

/**
 * 本地存储服务类
 * 封装LocalStorage操作，提供类型安全的存储接口
 */
export class LocalStorageService {
  private static instance: LocalStorageService

  private constructor() {}

  /**
   * 获取单例实例
   */
  public static getInstance(): LocalStorageService {
    if (!LocalStorageService.instance) {
      LocalStorageService.instance = new LocalStorageService()
    }
    return LocalStorageService.instance
  }

  /**
   * 检查浏览器是否支持LocalStorage
   */
  private isLocalStorageSupported(): boolean {
    try {
      const test = '__localStorage_test__'
      localStorage.setItem(test, test)
      localStorage.removeItem(test)
      return true
    } catch (e) {
      return false
    }
  }

  /**
   * 安全地设置存储项
   */
  private setItem(key: string, value: any): boolean {
    try {
      if (!this.isLocalStorageSupported()) {
        console.warn('LocalStorage is not supported')
        return false
      }
      
      const serializedValue = JSON.stringify(value)
      localStorage.setItem(key, serializedValue)
      return true
    } catch (error) {
      console.error('Failed to set localStorage item:', error)
      return false
    }
  }

  /**
   * 安全地获取存储项
   */
  private getItem<T>(key: string, defaultValue?: T): T | null {
    try {
      if (!this.isLocalStorageSupported()) {
        return defaultValue || null
      }
      
      const item = localStorage.getItem(key)
      if (item === null) {
        return defaultValue || null
      }
      
      return JSON.parse(item) as T
    } catch (error) {
      console.error('Failed to get localStorage item:', error)
      return defaultValue || null
    }
  }

  /**
   * 安全地删除存储项
   */
  private removeItem(key: string): boolean {
    try {
      if (!this.isLocalStorageSupported()) {
        return false
      }
      
      localStorage.removeItem(key)
      return true
    } catch (error) {
      console.error('Failed to remove localStorage item:', error)
      return false
    }
  }

  /**
   * 获取所有笔记
   */
  public getNotes(): Note[] {
    const notes = this.getItem<Note[]>('web-notes:notes', [])
    if (!notes) return []
    
    // 将字符串日期转换为Date对象
    return notes.map(note => ({
      ...note,
      createdAt: new Date(note.createdAt),
      updatedAt: new Date(note.updatedAt)
    }))
  }

  /**
   * 保存所有笔记
   */
  public saveNotes(notes: Note[]): boolean {
    return this.setItem('web-notes:notes', notes)
  }

  /**
   * 添加笔记
   */
  public addNote(note: Note): boolean {
    const notes = this.getNotes()
    const updatedNotes = [...notes, note]
    return this.saveNotes(updatedNotes)
  }

  /**
   * 更新笔记
   */
  public updateNote(updatedNote: Note): boolean {
    const notes = this.getNotes()
    const index = notes.findIndex(note => note.id === updatedNote.id)
    
    if (index === -1) {
      console.warn('Note not found:', updatedNote.id)
      return false
    }
    
    notes[index] = updatedNote
    return this.saveNotes(notes)
  }

  /**
   * 删除笔记
   */
  public deleteNote(noteId: string): boolean {
    const notes = this.getNotes()
    const filteredNotes = notes.filter(note => note.id !== noteId)
    
    if (filteredNotes.length === notes.length) {
      console.warn('Note not found:', noteId)
      return false
    }
    
    return this.saveNotes(filteredNotes)
  }

  /**
   * 根据ID获取笔记
   */
  public getNoteById(noteId: string): Note | null {
    const notes = this.getNotes()
    const note = notes.find(note => note.id === noteId)
    
    if (!note) {
      return null
    }
    
    return {
      ...note,
      createdAt: new Date(note.createdAt),
      updatedAt: new Date(note.updatedAt)
    }
  }

  /**
   * 获取应用设置
   */
  public getSettings(): AppSettings {
    const settings = this.getItem<AppSettings>('web-notes:settings')
    if (!settings) {
      // 返回默认设置
      return {
        autoSaveInterval: 3000,
        enableAutoSave: true,
        editorHeight: '500px',
        theme: 'light',
        fontSize: 14,
        showWordCount: true
      }
    }
    return settings
  }

  /**
   * 保存应用设置
   */
  public saveSettings(settings: AppSettings): boolean {
    return this.setItem('web-notes:settings', settings)
  }

  /**
   * 获取搜索历史
   */
  public getSearchHistory(): string[] {
    return this.getItem<string[]>('web-notes:search-history', []) || []
  }

  /**
   * 添加搜索历史
   */
  public addSearchHistory(query: string): boolean {
    if (!query.trim()) return false
    
    const history = this.getSearchHistory()
    const filteredHistory = history.filter(item => item !== query)
    const newHistory = [query, ...filteredHistory].slice(0, 10) // 最多保存10条
    
    return this.setItem('web-notes:search-history', newHistory)
  }

  /**
   * 清空搜索历史
   */
  public clearSearchHistory(): boolean {
    return this.removeItem('web-notes:search-history')
  }

  /**
   * 获取最近编辑的笔记ID
   */
  public getLastEditedNoteId(): string | null {
    return this.getItem<string>('web-notes:last-edited-note')
  }

  /**
   * 保存最近编辑的笔记ID
   */
  public saveLastEditedNoteId(noteId: string): boolean {
    return this.setItem('web-notes:last-edited-note', noteId)
  }

  /**
   * 清空所有数据
   */
  public clearAllData(): boolean {
    try {
      const keys = Object.keys(localStorage)
      const webNotesKeys = keys.filter(key => key.startsWith('web-notes:'))
      
      webNotesKeys.forEach(key => {
        localStorage.removeItem(key)
      })
      
      return true
    } catch (error) {
      console.error('Failed to clear all data:', error)
      return false
    }
  }

  /**
   * 获取存储使用情况
   */
  public getStorageUsage(): { used: number; total: number; percentage: number } {
    try {
      let used = 0
      const keys = Object.keys(localStorage)
      
      keys.forEach(key => {
        const item = localStorage.getItem(key)
        if (item) {
          used += new Blob([item]).size
        }
      })
      
      // 估算总容量 (通常为5-10MB)
      const total = 5 * 1024 * 1024 // 5MB
      const percentage = (used / total) * 100
      
      return { used, total, percentage }
    } catch (error) {
      console.error('Failed to get storage usage:', error)
      return { used: 0, total: 0, percentage: 0 }
    }
  }

  /**
   * 导出数据
   */
  public exportData(): { notes: Note[]; settings: AppSettings; searchHistory: string[] } {
    return {
      notes: this.getNotes(),
      settings: this.getSettings(),
      searchHistory: this.getSearchHistory()
    }
  }

  /**
   * 导入数据
   */
  public importData(data: { notes: Note[]; settings: AppSettings; searchHistory: string[] }): boolean {
    try {
      const success1 = this.saveNotes(data.notes)
      const success2 = this.saveSettings(data.settings)
      const success3 = this.setItem('web-notes:search-history', data.searchHistory)
      
      return success1 && success2 && success3
    } catch (error) {
      console.error('Failed to import data:', error)
      return false
    }
  }
}

// 导出单例实例
export const storageService = LocalStorageService.getInstance() 